<template>
  <div class="package-set">
    <a-form
      ref="formRef"
      :colon="false"
      autocomplete="off"
      :label-col="{ style: { width: '151px' } }"
      :model="formState"
      :rules="getFormRules"
      lableWidth
    >
      <a-form-item name="packageFlag" label="套餐自定义开关">
        <div class="form-item">
          <a-switch
            v-model:checked="formState.packageFlag"
            :disabled="operateType !== operateActionType.EDIT"
            :unCheckedValue="1"
            :checkedValue="2"
            un-checked-children="关闭"
            checked-children="启用"
          />
          <div class="item-info">
            <info-circle-outlined class="info-icon" />
            <span class="info-describe">说明：开启后，即可自定义渠道自定义信息</span>
          </div>
        </div>
      </a-form-item>
      <div class="global-drawer-title item-title">套餐自定义配置</div>
      <a-form-item name="ycHiddenFlag" label="是否隐藏财税BPai入口">
        <div class="form-item">
          <a-switch
            v-model:checked="formState.ycHiddenFlag"
            :disabled="operateType !== operateActionType.EDIT"
            :unCheckedValue="1"
            :checkedValue="2"
            un-checked-children="关闭"
            checked-children="启用"
          />
        </div>
      </a-form-item>
      <a-form-item name="msgWarnDays" label="套餐到期提醒">
        <div class="form-item">
          <template v-if="operateType === operateActionType.EDIT">
            <a-input-number
              class="item-number"
              :precision="0"
              placeholder="请输入"
              v-model:value="formState.msgWarnDays"
              :min="0"
              :max="99"
            />
            <span class="item-unit">天</span>
          </template>
          <div v-else class="item-value">{{ dayFormat(formState.msgWarnDays) }}天</div>

          <div class="item-info">
            <info-circle-outlined class="info-icon" />
            <span class="info-describe">说明：套餐/租户剩余有效时间小于该天数将发送预警消息</span>
          </div>
        </div>
      </a-form-item>
      <!-- <a-form-item name="formalFlag" label="正式套餐收费">
        <div class="form-item">
          <a-switch
            v-model:checked="formState.formalFlag"
            :disabled="operateType !== operateActionType.EDIT"
            :unCheckedValue="1"
            :checkedValue="2"
            un-checked-children="关闭"
            checked-children="启用"
          />
          <div class="item-info">
            <info-circle-outlined class="info-icon" />
            <span class="info-describe">说明：开启后新注册企业正式套餐将有时间限制</span>
          </div>
        </div>
      </a-form-item> -->

      <a-form-item name="tryFlag" label="企业试用">
        <div class="form-item">
          <a-switch
            v-model:checked="formState.tryFlag"
            :disabled="operateType !== operateActionType.EDIT"
            :unCheckedValue="1"
            :checkedValue="2"
            un-checked-children="停用"
            checked-children="启用"
          />

          <template v-if="formState.tryFlag === 2">
            <template v-if="operateType === operateActionType.EDIT">
              <a-form-item-rest>
                <a-input-number
                  class="item-number"
                  style="margin-left: 16px"
                  :precision="0"
                  placeholder="请输入"
                  v-model:value="formState.tryDays"
                  :min="0"
                  :max="30"
                />
                <span class="item-unit">天</span>
              </a-form-item-rest>
            </template>
            <div v-else class="item-value" style="margin-left: 16px">{{ dayFormat(formState.tryDays) }}天</div>
          </template>

          <div class="item-info">
            <info-circle-outlined class="info-icon" />
            <span class="info-describe">说明：开启开关后，新注册的企业将自动被授予您所设定的试用时长</span>
          </div>
        </div>
      </a-form-item>
      <!-- <a-form-item name="formalDays" label="正式企业有效时间">
        <div class="form-item">
          <template v-if="operateType === operateActionType.EDIT">
            <a-input-number
              class="item-number"
              :precision="0"
              placeholder="请输入"
              v-model:value="formState.formalDays"
              :min="0"
              :max="365"
            />
            <span class="item-unit">天</span>
          </template>
          <div v-else class="item-value">{{ dayFormat(formState.formalDays) }}天</div>
          <div class="item-info">
            <info-circle-outlined class="info-icon" />
            <span class="info-describe">说明：企业付款后开通正式企业的有效时间</span>
          </div>
        </div>
      </a-form-item> -->

      <!-- <a-form-item name="payUrl" label="付款链接">
        <div class="form-item">
          <a-input
            allowClear
            v-if="operateType === operateActionType.EDIT"
            class="item-input"
            placeholder="请输入获取付款二维码的链接"
            v-model:value.trim="formState.payUrl"
          >
          </a-input>
          <div v-else class="item-value">{{ formState.payUrl }}</div>
        </div>
      </a-form-item> -->
      <div class="uploadLogo uploadAlipay">
        <a-form-item name="alipayQrcode" label="支付宝收款码">
          <template v-if="operateType === operateActionType.EDIT">
            <a-upload
              v-model:alipayQrcodeList="alipayQrcodeList"
              name="customerlogo"
              list-type="picture-card"
              accept="image/png"
              class="avatar-uploader"
              :show-upload-list="false"
              :disabled="alipayLoading"
              :before-upload="beforeUpload"
              :customRequest="handleAliPayCodeRequest"
            >
              <template v-if="formState.alipayQrcode">
                <img :src="formState.alipayQrcode" alt="支付宝收款码" :width="126" :height="126" />
                <close-circle-filled class="file-close" @click.stop="formState.alipayQrcode = ''" />
              </template>
              <div class="inner-info" v-else style="width: 126px; height: 126px">
                <loading-outlined v-if="alipayLoading"></loading-outlined>
                <upload-outlined v-else></upload-outlined>
                <div class="ant-upload-text">上传图片</div>
              </div>
            </a-upload>
            <div class="upload-info">
              <info-circle-outlined class="info-icon" />
              只支持png格式，384*384px
            </div>
          </template>
          <div v-else>
            <a-image
              :width="126"
              :height="126"
              :src="formState.alipayQrcode"
              :preview="false"
              alt="联系客服二维码"
              v-if="formState.alipayQrcode"
            />
          </div>
        </a-form-item>
      </div>
      <a-form-item label="套餐授权" class="table-item">
        <div class="form-table drawer-table-empty">
          <a-table
            :scroll="{ y: 'calc(100vh - 366px)' }"
            bordered
            :columns="packageColumns"
            :dataSource="formState.packageList || []"
            :pagination="false"
          >
            <template #bodyCell="{ column, record, index }">
              <template v-if="column.dataIndex === 'packageName'">
                <EllipsisTooltip :title="record.packageName" :width="130">
                  {{ record.packageName }}
                </EllipsisTooltip>
              </template>
              <template v-else-if="column.dataIndex === 'channelUnitPrice'">
                <template v-if="operateType === operateActionType.EDIT">
                  <a-input-number
                    class="table-input"
                    :precision="0"
                    :controls="false"
                    v-model:value="record.channelUnitPrice"
                    :min="0"
                    :max="9999999"
                  />
                </template>
                <div v-else class="table-value">{{ record.channelUnitPrice }}</div>
              </template>
              <template v-else-if="column.dataIndex === 'channelBasePrice'">
                <template v-if="operateType === operateActionType.EDIT">
                  <a-input-number
                    class="table-input"
                    :precision="0"
                    :controls="false"
                    v-model:value="record.channelBasePrice"
                    :min="0"
                    :max="9999999"
                  />
                </template>
                <div v-else class="table-value">{{ record.channelBasePrice }}</div>
              </template>
              <template v-else-if="column.dataIndex === 'tryFlag'">
                <div
                  :class="['check-box', operateType === operateActionType.VIEW ? 'check-view' : '']"
                  @click="checkChange(record, 'tryFlag')"
                >
                  <div class="table-check" v-if="record.tryFlag == 2"></div>
                  <div class="table-uncheck" v-else></div>
                </div>
              </template>
              <template v-else-if="column.dataIndex === 'formalFlag'">
                <div
                  :class="['check-box', operateType === operateActionType.VIEW ? 'check-view' : '']"
                  @click="checkChange(record, 'formalFlag')"
                >
                  <div class="table-check" v-if="record.formalFlag == 2"></div>
                  <div class="table-uncheck" v-else></div>
                </div>
              </template>
            </template>
          </a-table>
        </div>
      </a-form-item>
    </a-form>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref, computed, unref, watch, onMounted } from 'vue'
import { operateActionType } from '@/types/enum'
import { message, Divider } from 'ant-design-vue'
import { InfoCircleOutlined, CloseCircleFilled, UploadOutlined, LoadingOutlined } from '@ant-design/icons-vue'
import EllipsisTooltip from '@/components/EllipsisTooltip/index.vue'
import type { UploadProps } from 'ant-design-vue'
import { cloneDeep, debounce } from 'lodash-es'
import { obsUpAndDownload } from '@/utils/file/obs'
import ObsClient from 'esdk-obs-browserjs/src/obs'
import api from '@/api'

const { updateChannelConfig, uploadLogo, generateChannelLoginUrlOrDownloadUrl, getPackageConfig, saveOrUpdate } = api
const emit = defineEmits(['operateSuccess', 'register'])

const props = defineProps({
  packageSetData: {
    type: Object,
    default: () => {}
  },
  operateType: {
    type: String,
    default: operateActionType.EDIT
  }
})
const alipayQrcodeList = ref([])
const alipayLoading = ref<boolean>(false)
let obsClient: any
let expiresTime: Date
const packageColumns = [
  {
    title: '套餐列表',
    align: 'center',
    width: 140,
    dataIndex: 'packageName'
  },
  {
    title: '标准价格（元）',
    align: 'center',
    dataIndex: 'unitPrice'
  },
  {
    title: '渠道售价（元）',
    align: 'center',
    width: 132,
    dataIndex: 'channelUnitPrice'
  },
  {
    title: '结算价格（元）',
    align: 'center',
    width: 132,
    dataIndex: 'channelBasePrice'
  },
  {
    title: '试用企业默认权限',
    align: 'center',
    width: 132,
    dataIndex: 'tryFlag'
  },
  {
    title: '正式企业默认权限',
    align: 'center',
    width: 132,
    dataIndex: 'formalFlag'
  }
]

const formState = reactive<any>({
  formalDays: null, // 正式企业套餐服务天数（正式套餐收费开启时-必填）
  // formalFlag: 1, // 正式套餐收费开关：1-关闭、2-开启，默认值:1-关闭
  msgWarnDays: null, // 到期提醒天数
  packageFlag: 0, // 套餐自定义开关：1-关闭、2-开启，默认值:1-关闭
  packageList: [], // 套餐列表
  payUrl: '', // 付款链接
  tryDays: null, // 试用企业套餐服务天数（企业试用开启时-必填）
  tryFlag: 1, // 企业试用开关：1-关闭、2-开启，默认值:1-关闭
  ycHiddenFlag: 1, // 是否隐藏业财360入口及菜单：1-关闭、2-开启，默认值:1-关闭
  alipayQrcode: '' //支付宝付款二维码
})
// 表单校验规则
const getFormRules = {
  packageFlag: [{ required: true, trigger: 'blur' }]
}

const getInitData = () => {
  Object.assign(formState, cloneDeep(props.packageSetData))
}
// 校验文件格式
const beforeUpload: UploadProps['beforeUpload'] = (file) => {
  const isImage = file.type.startsWith('image/')
  if (!isImage) {
    message.error('请上传图片文件')
    return false
  }
  return true
}
const getObsClient = async () => {
  let res = await uploadLogo({
    dir: `psy-public/${import.meta.env.VITE_OBS_DIR}/UI/channel`
  })
  let result = res.result
  expiresTime = new Date(result.expires_at)
  console.log('到期时间=====>', expiresTime)
  obsClient = new ObsClient({
    access_key_id: result.access, // 你的ak
    secret_access_key: result.secret, // 你的sk
    security_token: result.securitytoken,
    server: result.server // 你的endPoint
  })
}
onMounted(async () => {
  await getObsClient()
})
// 支付宝付款码上传
const handleAliPayCodeRequest = async (options: any) => {
  try {
    alipayLoading.value = true
    await getObsClient()
    formState.alipayQrcode = await obsUpAndDownload(obsClient, options)
    alipayLoading.value = false
  } catch (error) {
    alipayLoading.value = false
  }
}
watch(
  () => props.packageSetData,
  (newVal, oldVal) => {
    if (newVal && newVal.packageFlag) {
      getInitData()
    }
  },
  { deep: true }
)

const checkChange = (dataRecord: any, type: string) => {
  if (props.operateType === operateActionType.VIEW) {
    return
  }
  if (dataRecord.formalTryFlag) {
    return message.warning('该套餐为必选套餐，不可取消')
  }
  dataRecord[type] = dataRecord[type] == 2 ? 1 : 2
}
// 数据显示格式化
const dayFormat = (value: number | null) => {
  return value || value == 0 ? value : '--'
}
// 数据提交
const submitData = () => {
  // if (formState.packageFlag == 2 && !formState.formalDays && formState.formalDays != 0) {
  //   message.warning('请输入正式企业有效时间天数')
  //   return false
  // }
  if (formState.tryFlag == 2) {
    if (!formState.tryDays && formState.tryDays != 0) {
      message.warning('请输入试用企业有效时间天数')
      return false
    }
  }

  let packageList = formState.packageList
  if (packageList && packageList.length) {
    for (let i = 0; i < packageList.length; i++) {
      if (!packageList[i].channelUnitPrice && packageList[i].channelUnitPrice != 0) {
        message.warning('渠道售价不能为空')
        return false
      }
      if (!packageList[i].channelBasePrice && packageList[i].channelBasePrice != 0) {
        message.warning('结算价格不能为空')
        return false
      }
    }
  }
  formState.formalFlag = 2
  return cloneDeep(formState)
}

// 输出组件的方法，让外部组件可以调用
defineExpose({
  submitData
})
</script>
<style lang="less" scoped>
.package-set {
  .form-item {
    display: flex;
    align-items: center;
    .item-number {
      width: 96px;
    }
    .item-input {
      width: 408px;
    }
    .item-info {
      display: flex;
      align-items: center;
      margin-left: 24px;
      color: #c0c0c0;
      font-size: 12px;
      .info-icon {
        margin-right: 4px;
      }
    }
  }
  :deep(.table-item) {
    margin-bottom: 0;
  }
  :deep(.form-table) {
    overflow: hidden;
    .ant-table-tbody > tr.ant-table-row:hover > td,
    .ant-table-tbody > tr > td.ant-table-cell-row-hover {
      background: #fff;
    }
    .ant-table .ant-table-container .ant-table-tbody > tr > td {
      padding: 5px 5px;
      line-height: 22px;
    }
    .ant-table.ant-table-bordered > .ant-table-container {
      border-left: none;
    }
    .ant-table-body > table {
      margin-bottom: 24px;
    }
    .ant-table-header > table,
    .ant-table-body > table {
      border-left: 1px solid #e0e1e6;
    }

    .ant-table-thead > tr > th {
      color: #555d6f;
    }
    .table-input {
      width: 100%;
      .ant-input-number-input {
        text-align: center;
      }
    }
    .check-box {
      height: 32px;
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
      .table-check {
        width: 14px;
        height: 14px;
        background: #4aa353;
        border-radius: 50%;
        position: relative;
        &::after {
          content: '';
          position: absolute;
          width: 6px;
          height: 9px;
          border: 2px solid #fff;
          border-top: none;
          border-left: none;
          left: 4px;
          top: 1px;
          transform: rotate(45deg);
        }
      }
      .table-uncheck {
        width: 14px;
        height: 14px;
        border-radius: 50%;
        border: 1px solid #cdcdcd;
      }
      &.check-view {
        cursor: default;
        .table-uncheck {
          display: none;
        }
      }
    }
  }
  .item-title {
    margin-bottom: 24px;
  }
  .item-unit {
    color: #1b2134;
    line-height: 17px;
    font-size: 12px;
    margin-left: 8px;
  }
  .ant-switch-checked {
    background-color: #4aa353;
  }
}
.uploadLogo {
  margin: 40px 0;
  padding: 0 60px;
  &.uploadAlipay {
    padding: 0;
    margin: 0;
  }
  :deep(.ant-image-img) {
    background-color: #f3f4f8;
    width: 100%;
    height: 100%;
  }
  .avatar-uploader {
    position: relative;
    .file-close {
      font-size: 12px;
      color: #c0c0c0;
      position: absolute;
      right: 2px;
      top: 0;
      cursor: pointer;
      z-index: 999;
    }
  }

  :deep(.ant-form-item-no-colon) {
    height: 38px;
    align-items: center;
  }
  // .avatar-uploader > .ant-upload {
  //   width: 240px;
  //   height: 38px;
  // }
  :deep(.ant-upload) {
    position: relative;
    width: auto;
    height: auto;
    .inner-info {
      width: 240px;
      height: 38px;
      overflow: hidden;
      display: flex;
      align-items: center;
      justify-content: center;
    }
    img {
      background-color: #f3f4f8;
    }
  }
  .ant-upload-select-picture-card i {
    font-size: 12px;
    color: #999;
  }

  .ant-upload-select-picture-card .ant-upload-text {
    margin-left: 5px;
    font-size: 14px;
    font-family: PingFangSC-Medium, PingFang SC;
    font-weight: 500;
    color: #535d71;
  }
  :deep(.ant-form-itm-no-colon) {
    width: 61px;
    height: 22px;
    font-size: 12px;
    font-family: PingFangSC-Medium, PingFang SC;
    font-weight: 500;
    color: #192236;
    line-height: 22px;
  }
  :deep(.file-upload) {
    width: 242px;
    height: 40px;
    background: #ffffff;
    border-radius: 2px;
    border: 1px solid #cdcdcd;
  }
  .upload-info {
    color: #c0c0c0;
    font-size: 12px;
    .info-icon {
      font-size: 14px;
      margin-right: 4px;
    }
  }
}
</style>
